package jcu.ict.profaid;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class FormResultChart extends Activity {
	private AnswerDbAdapter adb;
	private QuestionDbAdapter qdb;
	private GraphicalView mChart;
	String selection = "bar";
	LinearLayout chartContainer;
	private String questionID;
	private Cursor aCursor;
	private Button btnCalculate;
	private String courseID;
	private String user_id;

	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.form_chart);

		adb = new AnswerDbAdapter(getBaseContext());
		qdb = new QuestionDbAdapter(getBaseContext());

		final Bundle bundle = this.getIntent().getExtras();
		questionID = bundle.getString("setQuestionId");
		courseID = bundle.getString("setCourseId");
		user_id = (String) bundle.getCharSequence("setUserId");

		chartContainer = (LinearLayout) findViewById(R.id.layoutChart);
		btnCalculate = (Button) findViewById(R.id.btnCalculate);

		adb.open();
		qdb.open();

		initViews();

		aCursor = adb.PopulateAnswer(user_id,questionID);
		aCursor.moveToFirst();

		chartBar(aCursor.getCount());

		btnCalculate.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				chartContainer.removeAllViewsInLayout();
				adb.open();
				qdb.open();
				Toast.makeText(getBaseContext(), selection, Toast.LENGTH_SHORT)
						.show();

				if (selection.equalsIgnoreCase("bar")) {
					initViews();

					aCursor = adb.PopulateAnswer(user_id,questionID);
					aCursor.moveToFirst();

					chartBar(aCursor.getCount());
				} else if (selection.equalsIgnoreCase("pie")) {
					initViews();
					
					aCursor = adb.PopulateAnswer(user_id,questionID);
					aCursor.moveToFirst();

					pieChart(aCursor.getCount());
				}

				adb.close();
				qdb.close();
			}
		});

		adb.close();
		qdb.close();
	}

	public void onRadioButtonClicked(final View view) {
		switch (view.getId()) {
		case R.id.radioBar:
			selection = "bar";
			break;
		case R.id.radioPie:
			selection = "pie";
			break;
		}

		if (selection.equalsIgnoreCase("bar")) {
			chartContainer.removeAllViewsInLayout();
			adb.open();

			initViews();
			aCursor = adb.PopulateAnswer(user_id,questionID);
			aCursor.moveToFirst();

			chartBar(aCursor.getCount());
			adb.close();
		} else if (selection.equalsIgnoreCase("pie")) {
			chartContainer.removeAllViewsInLayout();
			adb.open();
			Toast.makeText(getBaseContext(), selection, Toast.LENGTH_SHORT)
					.show();
			initViews();
			aCursor = adb.PopulateAnswer(user_id,questionID);
			aCursor.moveToFirst();

			pieChart(aCursor.getCount());
			adb.close();
		}

	}

	@SuppressWarnings("deprecation")
	private void chartBar(final int sumOfAnswer) {
		XYSeries series1;
		XYSeries series2;
		XYSeries series3;
		XYSeries series4;
		XYSeries series5;
		XYMultipleSeriesDataset dataset = null;
		XYSeriesRenderer renderer1;
		XYSeriesRenderer renderer2;
		XYSeriesRenderer renderer3;
		XYSeriesRenderer renderer4;
		XYSeriesRenderer renderer5;
		XYMultipleSeriesRenderer mRenderer = null;
		int sumAll = 0;

		if (sumOfAnswer == 2) {
			series1 = new XYSeries("Answer ID = " + aCursor.getString(2) + "\n");
			int sum1 = Integer.parseInt(aCursor.getString(1));
			series1.add(0.7, sum1);

			aCursor.moveToNext();
			series2 = new XYSeries("Answer ID = " + aCursor.getString(2));
			int sum2 = Integer.parseInt(aCursor.getString(1));
			series2.add(1.3, sum2);

			sumAll = sum1 + sum2;

			dataset = new XYMultipleSeriesDataset();
			dataset.addSeries(series1);
			dataset.addSeries(series2);

			renderer1 = new XYSeriesRenderer();
			renderer1.setDisplayChartValues(true);
			renderer1.setColor(Color.RED);
			renderer1.setChartValuesSpacing((float) 0.5);
			renderer1.setChartValuesTextSize(30);

			renderer2 = new XYSeriesRenderer();
			renderer2.setDisplayChartValues(true);
			renderer2.setColor(Color.GRAY);
			renderer2.setChartValuesTextSize(30);
			renderer2.setChartValuesSpacing((float) 1);

			mRenderer = new XYMultipleSeriesRenderer();

			mRenderer.addSeriesRenderer(renderer1);
			mRenderer.addSeriesRenderer(renderer2);
		}

		if (sumOfAnswer == 3) {
			series1 = new XYSeries("Answer ID = " + aCursor.getString(2) + "\n");
			int sum1 = Integer.parseInt(aCursor.getString(1));
			series1.add(0.5, sum1);

			aCursor.moveToNext();
			series2 = new XYSeries("Answer ID = " + aCursor.getString(2));
			int sum2 = Integer.parseInt(aCursor.getString(1));
			series2.add(1, sum2);

			aCursor.moveToNext();
			series3 = new XYSeries("Answer ID = " + aCursor.getString(2));
			int sum3 = Integer.parseInt(aCursor.getString(1));
			series3.add(1.5, sum3);

			sumAll = sum1 + sum2 + sum3;

			dataset = new XYMultipleSeriesDataset();
			dataset.addSeries(series1);
			dataset.addSeries(series2);
			dataset.addSeries(series3);

			renderer1 = new XYSeriesRenderer();
			renderer1.setDisplayChartValues(true);
			renderer1.setColor(Color.RED);
			renderer1.setChartValuesSpacing((float) 0.5);
			renderer1.setChartValuesTextSize(30);

			renderer2 = new XYSeriesRenderer();
			renderer2.setDisplayChartValues(true);
			renderer2.setColor(Color.GRAY);
			renderer2.setChartValuesTextSize(30);
			renderer2.setChartValuesSpacing((float) 1);

			renderer3 = new XYSeriesRenderer();
			renderer3.setDisplayChartValues(true);
			renderer3.setColor(Color.BLUE);
			renderer3.setChartValuesSpacing((float) 2);
			renderer3.setChartValuesTextSize(30);

			mRenderer = new XYMultipleSeriesRenderer();

			mRenderer.addSeriesRenderer(renderer1);
			mRenderer.addSeriesRenderer(renderer2);
			mRenderer.addSeriesRenderer(renderer3);
		}

		if (sumOfAnswer == 4) {
			series1 = new XYSeries("Answer ID = " + aCursor.getString(2) + "\n");
			int sum1 = Integer.parseInt(aCursor.getString(1));
			series1.add(0.5, sum1);

			aCursor.moveToNext();
			series2 = new XYSeries("Answer ID = " + aCursor.getString(2));
			int sum2 = Integer.parseInt(aCursor.getString(1));
			series2.add(0.75, sum2);

			aCursor.moveToNext();
			series3 = new XYSeries("Answer ID = " + aCursor.getString(2));
			int sum3 = Integer.parseInt(aCursor.getString(1));
			series3.add(1, sum3);

			aCursor.moveToNext();
			series4 = new XYSeries("Answer ID = " + aCursor.getString(2));
			int sum4 = Integer.parseInt(aCursor.getString(1));
			series4.add(1.25, sum4);

			sumAll = sum1 + sum2 + sum3 + sum4;

			dataset = new XYMultipleSeriesDataset();
			dataset.addSeries(series1);
			dataset.addSeries(series2);
			dataset.addSeries(series3);
			dataset.addSeries(series4);

			renderer1 = new XYSeriesRenderer();
			renderer1.setDisplayChartValues(true);
			renderer1.setColor(Color.RED);
			renderer1.setChartValuesSpacing((float) 0.5);
			renderer1.setChartValuesTextSize(30);

			renderer2 = new XYSeriesRenderer();
			renderer2.setDisplayChartValues(true);
			renderer2.setColor(Color.GREEN);
			renderer2.setChartValuesTextSize(30);
			renderer2.setChartValuesSpacing((float) 1);

			renderer3 = new XYSeriesRenderer();
			renderer3.setDisplayChartValues(true);
			renderer3.setColor(Color.BLUE);
			renderer3.setChartValuesSpacing((float) 2);
			renderer3.setChartValuesTextSize(30);

			renderer4 = new XYSeriesRenderer();
			renderer4.setDisplayChartValues(true);
			renderer4.setColor(Color.MAGENTA);
			renderer4.setChartValuesSpacing((float) 2);
			renderer4.setChartValuesTextSize(30);

			mRenderer = new XYMultipleSeriesRenderer();

			mRenderer.addSeriesRenderer(renderer1);
			mRenderer.addSeriesRenderer(renderer2);
			mRenderer.addSeriesRenderer(renderer3);
			mRenderer.addSeriesRenderer(renderer4);
		}
		
		if (sumOfAnswer == 5) {
			series1 = new XYSeries("Answer ID = " + aCursor.getString(2) + "\n");
			int sum1 = Integer.parseInt(aCursor.getString(1));
			series1.add(0.5, sum1);

			aCursor.moveToNext();
			series2 = new XYSeries("Answer ID = " + aCursor.getString(2));
			int sum2 = Integer.parseInt(aCursor.getString(1));
			series2.add(0.75, sum2);

			aCursor.moveToNext();
			series3 = new XYSeries("Answer ID = " + aCursor.getString(2));
			int sum3 = Integer.parseInt(aCursor.getString(1));
			series3.add(1, sum3);

			aCursor.moveToNext();
			series4 = new XYSeries("Answer ID = " + aCursor.getString(2));
			int sum4 = Integer.parseInt(aCursor.getString(1));
			series4.add(1.25, sum4);
			
			aCursor.moveToNext();
			series5 = new XYSeries("Answer ID = " + aCursor.getString(2));
			int sum5 = Integer.parseInt(aCursor.getString(1));
			series5.add(1.5, sum5);

			sumAll = sum1 + sum2 + sum3 + sum4 + sum5;

			dataset = new XYMultipleSeriesDataset();
			dataset.addSeries(series1);
			dataset.addSeries(series2);
			dataset.addSeries(series3);
			dataset.addSeries(series4);
			dataset.addSeries(series5);

			renderer1 = new XYSeriesRenderer();
			renderer1.setDisplayChartValues(true);
			renderer1.setColor(Color.RED);
			renderer1.setChartValuesSpacing((float) 0.5);
			renderer1.setChartValuesTextSize(30);

			renderer2 = new XYSeriesRenderer();
			renderer2.setDisplayChartValues(true);
			renderer2.setColor(Color.GREEN);
			renderer2.setChartValuesTextSize(30);
			renderer2.setChartValuesSpacing((float) 1);

			renderer3 = new XYSeriesRenderer();
			renderer3.setDisplayChartValues(true);
			renderer3.setColor(Color.BLUE);
			renderer3.setChartValuesSpacing((float) 1);
			renderer3.setChartValuesTextSize(30);

			renderer4 = new XYSeriesRenderer();
			renderer4.setDisplayChartValues(true);
			renderer4.setColor(Color.MAGENTA);
			renderer4.setChartValuesSpacing((float) 1);
			renderer4.setChartValuesTextSize(30);
			
			renderer5 = new XYSeriesRenderer();
			renderer5.setDisplayChartValues(true);
			renderer5.setColor(Color.MAGENTA);
			renderer5.setChartValuesSpacing((float) 1);
			renderer5.setChartValuesTextSize(30);

			mRenderer = new XYMultipleSeriesRenderer();

			mRenderer.addSeriesRenderer(renderer1);
			mRenderer.addSeriesRenderer(renderer2);
			mRenderer.addSeriesRenderer(renderer3);
			mRenderer.addSeriesRenderer(renderer4);
			mRenderer.addSeriesRenderer(renderer5);
		}

		// Creating a XYMultipleSeriesRenderer to customize the whole chart
		double[] range = { 0, 0, 0, 0 };
		mRenderer.setLegendHeight(60);
		mRenderer.setScale(1.5f);
		mRenderer.setBarSpacing(-0.9f);
		mRenderer.setAxesColor(Color.WHITE);
		mRenderer.setInitialRange(range, 1);
		mRenderer.setXAxisMin(0);
		mRenderer.setXAxisMax(2);
		mRenderer.setYAxisMax(sumAll);
		mRenderer.setYAxisMin(0);
		mRenderer.setXLabelsAlign(Align.RIGHT);
		mRenderer.setYLabelsAlign(Align.RIGHT);
		mRenderer.setPanEnabled(false, false);
		mRenderer.setYTitle("Total of Answer");
		mRenderer.setAxisTitleTextSize(18);
		mRenderer.setLegendTextSize(20);
		mRenderer.setLabelsTextSize(15);

		mChart = ChartFactory.getBarChartView(getBaseContext(), dataset,
				mRenderer, Type.DEFAULT);

		chartContainer.addView(mChart);

	}

	private void pieChart(int sumOfAnswer) {

		CategorySeries series = null;
		int[] colors = null;

		if (sumOfAnswer == 2) {
			int sum1 = Integer.parseInt(aCursor.getString(1));
			String ID1 = aCursor.getString(2);

			aCursor.moveToNext();
			int sum2 = Integer.parseInt(aCursor.getString(1));
			String ID2 = aCursor.getString(2);

			int values[] = { sum1, sum2 };
			String ID[] = { ID1, ID2 };

			series = new CategorySeries("PIE CHART");

			for (int i = 0; i < values.length; i++) {
				series.add("Answer Id =" + ID[i], values[i]);
			}
			
			colors = new int[] { Color.CYAN, Color.MAGENTA };
		}

		if (sumOfAnswer == 3) {
			int sum1 = Integer.parseInt(aCursor.getString(1));
			String ID1 = aCursor.getString(2);

			aCursor.moveToNext();
			int sum2 = Integer.parseInt(aCursor.getString(1));
			String ID2 = aCursor.getString(2);

			aCursor.moveToNext();
			int sum3 = Integer.parseInt(aCursor.getString(1));
			String ID3 = aCursor.getString(2);

			int values[] = { sum1, sum2, sum3 };
			String ID[] = { ID1, ID2, ID3 };

			series = new CategorySeries("PIE CHART");

			for (int i = 0; i < values.length; i++) {
				series.add("Answer Id =" + ID[i], values[i]);
			}

			colors = new int[] { Color.CYAN, Color.BLUE, Color.MAGENTA };
		}

		if (sumOfAnswer == 4) {
			int sum1 = Integer.parseInt(aCursor.getString(1));
			String ID1 = aCursor.getString(2);

			aCursor.moveToNext();
			int sum2 = Integer.parseInt(aCursor.getString(1));
			String ID2 = aCursor.getString(2);

			aCursor.moveToNext();
			int sum3 = Integer.parseInt(aCursor.getString(1));
			String ID3 = aCursor.getString(2);

			aCursor.moveToNext();
			int sum4 = Integer.parseInt(aCursor.getString(1));
			String ID4 = aCursor.getString(2);

			int values[] = { sum1, sum2, sum3, sum4 };
			String ID[] = { ID1, ID2, ID3, ID4 };

			series = new CategorySeries("PIE CHART");

			for (int i = 0; i < values.length; i++) {
				series.add("Answer Id =" + ID[i], values[i]);
			}

			colors = new int[] { Color.RED, Color.CYAN, Color.BLUE,
					Color.MAGENTA };
		}
		
		if (sumOfAnswer == 5) {
			int sum1 = Integer.parseInt(aCursor.getString(1));
			String ID1 = aCursor.getString(2);

			aCursor.moveToNext();
			int sum2 = Integer.parseInt(aCursor.getString(1));
			String ID2 = aCursor.getString(2);

			aCursor.moveToNext();
			int sum3 = Integer.parseInt(aCursor.getString(1));
			String ID3 = aCursor.getString(2);

			aCursor.moveToNext();
			int sum4 = Integer.parseInt(aCursor.getString(1));
			String ID4 = aCursor.getString(2);

			aCursor.moveToNext();
			int sum5 = Integer.parseInt(aCursor.getString(1));
			String ID5 = aCursor.getString(2);
			
			int values[] = { sum1, sum2, sum3, sum4, sum5 };
			String ID[] = { ID1, ID2, ID3, ID4, ID5 };

			series = new CategorySeries("PIE CHART");

			for (int i = 0; i < values.length; i++) {
				series.add("Answer Id =" + ID[i], values[i]);
			}

			colors = new int[] { Color.RED, Color.CYAN, Color.BLUE,
					Color.MAGENTA, Color.YELLOW };
		}

		DefaultRenderer renderer = new DefaultRenderer();
		for (int color : colors) {
			SimpleSeriesRenderer r = new SimpleSeriesRenderer();
			r.setColor(color);
			renderer.addSeriesRenderer(r);
			renderer.setLabelsTextSize(20);
			renderer.setLabelsColor(Color.BLACK);
		}

		mChart = ChartFactory.getPieChartView(getBaseContext(), series,
				renderer);

		chartContainer.addView(mChart);
	}

	public void initViews() {
		final Cursor iTimeDate = adb.getTimeCompare();
		iTimeDate.moveToFirst();

		final long dTime = iTimeDate.getLong(0);

		final Uri uriSms = Uri.parse("content://sms/inbox");
		final Cursor cursor = getContentResolver().query(uriSms,
				new String[] { "_id", "address", "date", "body" },
				"date" + ">" + dTime, null, null);

		String body;
		String smsId;

		if (cursor.moveToFirst()) {
			adb.updateTimeFlag(cursor.getLong(2));
			do {
				body = cursor.getString(3);
				smsId = cursor.getString(0);
				if (checkSMSvalue(body) == true) {
					deleteSms(smsId);
				}
			} while (cursor.moveToNext());
		} else {
		}
	}

	public boolean checkSMSvalue(final String answer) {
		boolean check = false;
		try {
			final int iAnswer = Integer.parseInt(answer);

			final Cursor cAnswer = adb.getAnswer(iAnswer);
			cAnswer.moveToFirst();

			for (int i = 0; i < cAnswer.getCount(); i++)
				for (int j = 0; j < cAnswer.getColumnCount(); j++) {
					final Cursor cAnswerSum = adb.getSum(cAnswer.getInt(j));
					cAnswerSum.moveToFirst();

					final int x = cAnswerSum.getInt(0);

					if (adb.updateAnswerSum(cAnswer.getInt(j), x)) {
						check = true;
						Toast.makeText(this, "Update successful.",
								Toast.LENGTH_LONG).show();
					} else {
						Toast.makeText(this, "Update failed.",
								Toast.LENGTH_LONG).show();
					}
				}
		} catch (final Exception e) {
		}
		return check;
	}

	public boolean deleteSms(final String smsId) {
		boolean isSmsDeleted = false;
		try {
			this.getContentResolver().delete(
					Uri.parse("content://sms/" + smsId), null, null);
			isSmsDeleted = true;

		} catch (final Exception ex) {
			isSmsDeleted = false;
		}
		return isSmsDeleted;
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
	    	Intent in = new Intent(FormResultChart.this,MainQuestion.class);
			Bundle bundle = new Bundle();
			bundle.putString("setInfoCourse", courseID);
			bundle.putCharSequence("setUserId", user_id);
            in.putExtras(bundle);
			startActivity(in);
			finish();
	    }
	    return super.onKeyDown(keyCode, event);
	}

}
